package org.komarichin;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Properties;

/**
 * User: Mykhaylo Komarichyn
 * Date: 10.02.2010
 * Time: 15:19:55
 */
public class Configurator {

    private static final Logger log = LoggerFactory.getLogger(Configurator.class);

    private Properties props;
    private Properties keyProps;

    public String getPropValue(String key) {
        Properties p = null;
        try {
            p = getProps();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return p != null ? p.getProperty(key) : null;
    }

    public String getServerBasePath() {
        HttpServletRequest req = ServletActionContext.getRequest();
        return "http://" + req.getHeader("Host");
    }

    public String getKey(String key) {
        Properties p = null;
        try {
            p = getKeyProps();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return p != null ? p.getProperty(key) : null;
    }

    public Properties getKeyProps() throws IOException {
        if (keyProps == null) {
            keyProps = new Properties();
            keyProps.load(getClass().getResourceAsStream("/keys.properties"));
        }
        return keyProps;
    }

    public Properties getProps() throws IOException {
        if (props == null) {
            props = new Properties();
            props.load(getClass().getResourceAsStream("/struts.properties"));
        }
        return props;
    }
}
